package com.zy.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 这是那头猪？
 * @version 1.0
 * @description: TODO
 * @date 2023/6/6 9:57
 */
@Component
// 自定义类要实现  BlockExceptionHandler
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                       BlockException e) throws IOException {
        //设置响应的字符集 和 类型
        httpServletResponse.setContentType("text/plain;charset=UTF-8");
        // 根据不同的BlockException类型进行不同的处理逻辑
        if (e instanceof FlowException) {
            // 处理限流异常
            httpServletResponse.getWriter().write("服务限流了");
        } else if (e instanceof DegradeException) {
            // 处理降级异常
            httpServletResponse.getWriter().write("服务降级了");
        } else if (e instanceof ParamFlowException) {
            //
            httpServletResponse.getWriter().write("热点参数被修改了");
        }else if (e instanceof SystemBlockException) {
            httpServletResponse.getWriter().write("触发系统保护规则了");
        }else if (e instanceof AuthorityException) {
            httpServletResponse.getWriter().write("授权规则不通过");
        }
        // BlockException 还有一些其他的子异常，可以判断类型根据类型返回结果
    }
}